// pages/partList/partList.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参来的设备信息
    fromParam:null,
    //设备类型
    typeArr:[],
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,
    //设备类型名称
    typeNames:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.fromParam){
      this.setData({
        fromParam: JSON.parse(options.fromParam)
      })
      //查询设备类型
      this.getEquipmentType();
      //获取配件列表
      this.getList();
    }
  },

  //修改设备分类
  goToEditType(){
    let paramPartList={
      ids:this.data.typeArr,
      names:this.data.typeNames
    }
    wx.navigateTo({
      url: "/pages/equipmenType/equipmenType?paramPartList="+JSON.stringify(paramPartList)+"&id="+this.data.fromParam.id
    })
  },

  //查询设备类型
  getEquipmentType(){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        id: this.data.fromParam.id,
        selectFields: ["id", "typeArr"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        if(result.typeArr && result.typeArr.length){
          this.setData({
            typeArr: result.typeArr
          })
          //查询设备类型名称
          this.getTypeInfo();
        }else{
          wx.navigateTo({
            url: "/pages/equipmenType/equipmenType?id="+this.data.fromParam.id
          })
        }
      }
    }).catch((error) => {
    })
  },

  //查询设备类型名称
  getTypeInfo(){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        id: this.data.typeArr,
        selectFields: ["id","fid","name"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push(item.name);
        });
        this.setData({
          typeNames: arr.join(' - ')
        })
      }
    }).catch((error) => {
    })
  },

  //获取配件列表
  getList(){
    let param={
      source:"小程序，配件列表，查询配件",
      className:"com.jbn.model.part.Part",
      checkDataAuthority:false,
      condition:[{
        fieldName:"equipmentId",
        relation:"=",
        value: this.data.fromParam.id
      }],
      lookup: [{
        localField: "partType",
        foreignField: "id",
        fromClassName: "com.jbn.model.part.PartBase",
        asField: "partTypeObj"
      }],
      groups:{
        groupFileds:[{name:"partType",target:"$partType"}],
        childKey:"result"
      },
      resultClassName:"com.jbn.mongo.nb.model.GroupResultModel",
      page: {
        page: this.data.page,
        rows: 10
      }
    }

    CommonService.findList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        if(list.length){
          list.forEach(itemr => {
            let result=itemr.result;
            if(result[0].result.partTypeObj.length){
              itemr.typeName=result[0].result.partTypeObj[0].name;
            }
            result.forEach(item => {
              item.showDetail=false;
              //只显示有值的参数
              let partParams=item.result.partParams;
              item.partParamsHave=[];
              for(let i=0;i<partParams.length;i++){
                if(partParams[i].value){
                  item.partParamsHave.push(partParams[i]);
                }
              }
            });
          });

          console.log('配件列表');
          console.log(list);

          this.setData({
            list: this.data.list.concat(list)
          });

        }else{
          this.setData({
            notMore: false
          })
          if(this.data.page==1){
            this.setData({
              showNothing: true
            });
          }else{
            Toast.fail('没有更多了');
          }
        }
      }else{
        this.setData({
          showNothing: true
        });
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      });
    })
  },

  //展开详情
  onOpenDetails(e){
    let detail=e.currentTarget.dataset.detail;
    let list=this.data.list;

    for(let i=0;i<list.length;i++){
      let arr=list[i].result;
      arr.forEach(item => {
        if (item.result.id==detail.id){
          item.showDetail=!(item.showDetail);
        }
      });
    }

    this.setData({
			list: list
		})
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //跳转添加配件
  goToAdd(e) {
    let typeArr=this.data.typeArr;
    if(typeArr.length){
      wx.navigateTo({
        url: "/pages/partAdd/partAdd?equipmentId="+this.data.fromParam.id+"&typeArr="+JSON.stringify(typeArr)
      })
    }else{
      wx.navigateTo({
        url: "/pages/equipmenType/equipmenType?id="+this.data.fromParam.id
      })
    }
  },

  //跳转编辑
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/partAdd/partAdd?id="+detail.id
		})
  },

  //显示删除确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showDelete: true,
      deleteId:detail.id
		})
  },

  //隐藏删除确认框
  onCloseDelete(){
    this.setData({
			showDelete: false
		})
  },

  //确认删除
  confirmDelete(){
    let param={
      className:"part",
      data:{
        id:this.data.deleteId
      }
    }

    CommonService.goDelete(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        //刷新列表和页码
        this.refreshListAndPage();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;
    wx.previewImage({
      current: src,
      urls: detail
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
